import nmap
import optparse
from threading import *
#screenLock=Semaphore(value=1)#用于锁定屏幕，防止占用

def nmapScan(tgtHost,tgtPort):
    nmScan=nmap.PortScanner()
    nmScan.scan(tgtHost,tgtPort)
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    #screenLock.acquire()
    print("[*]"+tgtHost+" tcp/"+tgtPort+" "+state)
    #screenLock.release()
def main():
    # 命令行参数解析
    parser = optparse.OptionParser('usage %prog' + '-H <target host> -p <target port>')
    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')  # 单个输入
    duanPost = str(options.tgtPort).split('-')  # 段输入
    if tgtHost == None or tgtPorts[0] == None:
        print('[-] You must specify a target host and port[s].')
        exit(0)
    try:
        if duanPost[1] != None:
            tgtPorts = []
            for i in range(int(duanPost[0]), int(duanPost[1])+1):
                tgtPorts.append(str(i))
    except:
        pass
    for tgtPort in tgtPorts:
        nmapScan(tgtHost,tgtPort)
    # print(tgtPorts)

    # threads=[]
    # for tgtPort in tgtPorts:
    #     try:
    #         t=Thread(target=nmapScan,args=(tgtHost,tgtPort))
    #         threads.append(t)
    #     except:
    #         break
    # for thread in threads:
    #     thread.start()
    # for thread in threads:
    #     thread.join()

if __name__ == '__main__':
    main()